package com.ruoyi.functiontest.controller;

import java.util.List;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.functiontest.domain.TollDataSummaryTest;
import com.ruoyi.functiontest.service.ITollDataSummaryTestService;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 收费数据汇总测试Controller
 * 
 * @author ruoyi
 * @date 2025-09-25
 */
@RestController
@RequestMapping("/functiontest/TollDataSummaryTest")
public class TollDataSummaryTestController extends BaseController
{
    @Autowired
    private ITollDataSummaryTestService tollDataSummaryTestService;

    /**
     * 查询收费数据汇总测试列表
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollDataSummaryTest:list')")
    @GetMapping("/list")
    public AjaxResult list(TollDataSummaryTest tollDataSummaryTest)
    {
        List<TollDataSummaryTest> list = tollDataSummaryTestService.selectTollDataSummaryTestList(tollDataSummaryTest);
        
        // 判断是否有搜索条件，如果有则构建树形结构返回
        boolean hasSearchCondition = tollDataSummaryTest.getRoadName() != null && !tollDataSummaryTest.getRoadName().isEmpty() ||
                                   tollDataSummaryTest.getNodeName() != null && !tollDataSummaryTest.getNodeName().isEmpty();
        
        if (hasSearchCondition) {
            // 有搜索条件时，构建树形结构返回，包含匹配节点及其所有子节点
            List<TollDataSummaryTest> treeList = buildTree(list);
            return success(treeList);
        } else {
            // 无搜索条件时，返回扁平列表
            return success(list);
        }
    }

    /**
     * 导出收费数据汇总测试列表
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollDataSummaryTest:export')")
    @Log(title = "收费数据汇总测试", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TollDataSummaryTest tollDataSummaryTest)
    {
        // 简化导出逻辑：直接导出数据库原始存储格式，无需树形结构处理
        List<TollDataSummaryTest> list = tollDataSummaryTestService.selectTollDataSummaryTestList(tollDataSummaryTest);
        
        ExcelUtil<TollDataSummaryTest> util = new ExcelUtil<TollDataSummaryTest>(TollDataSummaryTest.class);
        util.exportExcel(response, list, "收费数据汇总测试数据");
    }

    /**
     * 获取收费数据汇总测试详细信息
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollDataSummaryTest:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tollDataSummaryTestService.selectTollDataSummaryTestById(id));
    }

    /**
     * 新增收费数据汇总测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollDataSummaryTest:add')")
    @Log(title = "收费数据汇总测试", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TollDataSummaryTest tollDataSummaryTest)
    {
        return toAjax(tollDataSummaryTestService.insertTollDataSummaryTest(tollDataSummaryTest));
    }

    /**
     * 修改收费数据汇总测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollDataSummaryTest:edit')")
    @Log(title = "收费数据汇总测试", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TollDataSummaryTest tollDataSummaryTest)
    {
        return toAjax(tollDataSummaryTestService.updateTollDataSummaryTest(tollDataSummaryTest));
    }

    /**
     * 删除收费数据汇总测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollDataSummaryTest:remove')")
    @Log(title = "收费数据汇总测试", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        // 检查是否存在子节点
        for (Long id : ids) {
            if (tollDataSummaryTestService.hasChildById(id)) {
                return AjaxResult.error("存在下级数据，不允许删除！");
            }
        }
        return toAjax(tollDataSummaryTestService.deleteTollDataSummaryTestByIds(ids));
    }
    
    /**
     * 导入收费数据汇总测试数据
     * 简化导入逻辑：直接按照Excel原始格式导入，通过id和parentid来确定数据
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollDataSummaryTest:import')")
    @Log(title = "收费数据汇总测试", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<TollDataSummaryTest> util = new ExcelUtil<TollDataSummaryTest>(TollDataSummaryTest.class);
        List<TollDataSummaryTest> importList = util.importExcel(file.getInputStream());
        
        String message = tollDataSummaryTestService.importTollDataSummaryTest(importList, updateSupport);
        return success(message);
    }

    /**
     * 导入模板下载
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollDataSummaryTest:import')")
    @GetMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        List<TollDataSummaryTest> list = new ArrayList<>();
        
        // 添加示例数据 - 六安路段
        TollDataSummaryTest data1 = new TollDataSummaryTest();
        data1.setId(1L);
        data1.setParentId(0L);
        data1.setRoadName("六安");
        data1.setNodeName("");
        data1.setMeasureLength(null);
        data1.setRemark("");
        list.add(data1);
        
        TollDataSummaryTest data2 = new TollDataSummaryTest();
        data2.setId(2L);
        data2.setParentId(1L);
        data2.setRoadName("");
        data2.setNodeName("主线");
        data2.setMeasureLength(new BigDecimal("151.660"));
        data2.setRemark("包含收费桥隧");
        list.add(data2);
        
        TollDataSummaryTest data3 = new TollDataSummaryTest();
        data3.setId(3L);
        data3.setParentId(1L);
        data3.setRoadName("");
        data3.setNodeName("收费隧道（双幅隧道）");
        data3.setMeasureLength(new BigDecimal("27.770"));
        data3.setRemark("共计18座收费双幅隧道");
        list.add(data3);
        
        TollDataSummaryTest data4 = new TollDataSummaryTest();
        data4.setId(4L);
        data4.setParentId(1L);
        data4.setRoadName("");
        data4.setNodeName("收费桥梁（双幅桥梁）");
        data4.setMeasureLength(new BigDecimal("17.150"));
        data4.setRemark("共计18座收费双幅桥梁");
        list.add(data4);
        
        TollDataSummaryTest data5 = new TollDataSummaryTest();
        data5.setId(5L);
        data5.setParentId(1L);
        data5.setRoadName("");
        data5.setNodeName("匝道");
        data5.setMeasureLength(new BigDecimal("13.620"));
        data5.setRemark("包含全部枢纽互通");
        list.add(data5);
        
        TollDataSummaryTest data6 = new TollDataSummaryTest();
        data6.setId(6L);
        data6.setParentId(1L);
        data6.setRoadName("");
        data6.setNodeName("匝道汇聚点至收费站中心长度");
        data6.setMeasureLength(new BigDecimal("2.310"));
        data6.setRemark("包含全部收费站");
        list.add(data6);
        
        TollDataSummaryTest data7 = new TollDataSummaryTest();
        data7.setId(7L);
        data7.setParentId(1L);
        data7.setRoadName("");
        data7.setNodeName("引道");
        data7.setMeasureLength(new BigDecimal("9.720"));
        data7.setRemark("包含全部引道");
        list.add(data7);
        
        // 添加示例数据 - 纳晴路段
        TollDataSummaryTest data8 = new TollDataSummaryTest();
        data8.setId(8L);
        data8.setParentId(0L);
        data8.setRoadName("纳晴");
        data8.setNodeName("");
        data8.setMeasureLength(null);
        data8.setRemark("");
        list.add(data8);
        
        TollDataSummaryTest data9 = new TollDataSummaryTest();
        data9.setId(9L);
        data9.setParentId(8L);
        data9.setRoadName("");
        data9.setNodeName("主线");
        data9.setMeasureLength(new BigDecimal("161.020"));
        data9.setRemark("包含收费桥隧");
        list.add(data9);
        
        TollDataSummaryTest data10 = new TollDataSummaryTest();
        data10.setId(10L);
        data10.setParentId(8L);
        data10.setRoadName("");
        data10.setNodeName("收费隧道（双幅隧道）");
        data10.setMeasureLength(new BigDecimal("66.703"));
        data10.setRemark("共计30座收费双幅隧道");
        list.add(data10);
        
        TollDataSummaryTest data11 = new TollDataSummaryTest();
        data11.setId(11L);
        data11.setParentId(8L);
        data11.setRoadName("");
        data11.setNodeName("收费隧道（单幅隧道）");
        data11.setMeasureLength(new BigDecimal("2.117"));
        data11.setRemark("共计1座收费单幅隧道");
        list.add(data11);
        
        TollDataSummaryTest data12 = new TollDataSummaryTest();
        data12.setId(12L);
        data12.setParentId(8L);
        data12.setRoadName("");
        data12.setNodeName("收费桥梁（双幅桥梁）");
        data12.setMeasureLength(new BigDecimal("31.321"));
        data12.setRemark("共计31座收费双幅桥梁");
        list.add(data12);
        
        TollDataSummaryTest data13 = new TollDataSummaryTest();
        data13.setId(13L);
        data13.setParentId(8L);
        data13.setRoadName("");
        data13.setNodeName("收费桥梁（单幅桥梁）");
        data13.setMeasureLength(new BigDecimal("1.892"));
        data13.setRemark("共计2座收费单幅桥梁");
        list.add(data13);
        
        TollDataSummaryTest data14 = new TollDataSummaryTest();
        data14.setId(14L);
        data14.setParentId(8L);
        data14.setRoadName("");
        data14.setNodeName("匝道");
        data14.setMeasureLength(new BigDecimal("66.670"));
        data14.setRemark("包含全部互通及匝道桥");
        list.add(data14);
        
        TollDataSummaryTest data15 = new TollDataSummaryTest();
        data15.setId(15L);
        data15.setParentId(8L);
        data15.setRoadName("");
        data15.setNodeName("匝道汇聚点至收费站中心长度");
        data15.setMeasureLength(new BigDecimal("4.323"));
        data15.setRemark("包含全部收费站");
        list.add(data15);
        
        TollDataSummaryTest data16 = new TollDataSummaryTest();
        data16.setId(16L);
        data16.setParentId(8L);
        data16.setRoadName("");
        data16.setNodeName("引道");
        data16.setMeasureLength(new BigDecimal("15.163"));
        data16.setRemark("包含全部引道及引道单幅隧道");
        list.add(data16);
        
        ExcelUtil<TollDataSummaryTest> util = new ExcelUtil<TollDataSummaryTest>(TollDataSummaryTest.class);
        util.exportExcel(response, list, "收费数据汇总测试导入模板");
    }
    
    /**
     * 实测单位批量审核
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollDataSummaryTest:fieldAudit')")
    @Log(title = "收费数据汇总测试", businessType = BusinessType.UPDATE)
    @PostMapping("/fieldAudit/batch")
    public AjaxResult fieldAuditBatch()
    {
        try {
            // 批量更新所有记录的review1字段为0
            int updatedCount = tollDataSummaryTestService.updateReview1ToZero();
            System.out.println("实测单位批量审核完成，更新记录数：" + updatedCount);
            return success("实测单位批量审核成功，共更新" + updatedCount + "条记录");
        } catch (Exception e) {
            System.err.println("实测单位批量审核失败：" + e.getMessage());
            return error("实测单位批量审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 业主批量审核
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollDataSummaryTest:ownerAudit')")
    @Log(title = "收费数据汇总测试", businessType = BusinessType.UPDATE)
    @PostMapping("/ownerAudit/batch")
    public AjaxResult ownerAuditBatch(@RequestBody Map<String, Object> params)
    {
        try {
            Long deptId = params.get("deptId") != null ? Long.valueOf(params.get("deptId").toString()) : null;
            Long roleId = params.get("roleId") != null ? Long.valueOf(params.get("roleId").toString()) : null;
            
            System.out.println("业主批量审核 - 审核所有数据，deptId: " + deptId + ", roleId: " + roleId);
            
            // 1. 校验所有数据的review1字段是否都为0
            boolean allReview1Zero = tollDataSummaryTestService.checkAllReview1IsZero();
            if (!allReview1Zero) {
                return error("业主批量审核失败：存在未通过实测单位审核的数据，请先完成实测单位审核");
            }
            
            // 2. 构建查询条件
            TollDataSummaryTest queryCondition = new TollDataSummaryTest();
            queryCondition.setDeptId(deptId);
            queryCondition.setRoleId(roleId);
            
            // 3. 从params中提取查询条件
            if (params.get("roadName") != null) {
                queryCondition.setRoadName(params.get("roadName").toString());
            }
            if (params.get("nodeName") != null) {
                queryCondition.setNodeName(params.get("nodeName").toString());
            }
            
            // 4. 根据条件批量更新业主审核状态
            int updatedCount = tollDataSummaryTestService.updateReview2ToZeroByCondition(queryCondition);
            
            System.out.println("业主批量审核完成，更新记录数：" + updatedCount);
            return success("业主批量审核成功，共更新" + updatedCount + "条记录");
        } catch (Exception e) {
            System.err.println("业主批量审核失败：" + e.getMessage());
            return error("业主批量审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 中心批量审核
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollDataSummaryTest:centerAudit')")
    @Log(title = "收费数据汇总测试", businessType = BusinessType.UPDATE)
    @PostMapping("/centerAudit/batch")
    public AjaxResult centerAuditBatch()
    {
        try {
            System.out.println("中心批量审核 - 审核所有数据");
            
            // 1. 校验所有数据的review1和review2字段是否都不为空且都为0
            boolean allReview1AndReview2Zero = tollDataSummaryTestService.checkAllReview1AndReview2AreZero();
            if (!allReview1AndReview2Zero) {
                return error("中心批量审核失败：存在未通过实测单位审核或业主审核的数据，请先完成前序审核");
            }
            
            // 2. 批量更新中心审核状态
            int updatedCount = tollDataSummaryTestService.updateReview3ToZero();
            
            System.out.println("中心批量审核完成，更新记录数：" + updatedCount);
            return success("中心批量审核成功，共更新" + updatedCount + "条记录");
        } catch (Exception e) {
            System.err.println("中心批量审核失败：" + e.getMessage());
            return error("中心批量审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 构建树形结构
     */
    private List<TollDataSummaryTest> buildTree(List<TollDataSummaryTest> list) {
        // 构建父子关系映射
        Map<Long, TollDataSummaryTest> nodeMap = new HashMap<>();
        List<TollDataSummaryTest> rootNodes = new ArrayList<>();
        
        // 先将所有节点放入map中
        for (TollDataSummaryTest node : list) {
            nodeMap.put(node.getId(), node);
        }
        
        // 构建父子关系
        for (TollDataSummaryTest node : list) {
            Long parentId = node.getParentId();
            if (parentId != null && parentId != 0) {
                TollDataSummaryTest parent = nodeMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<TollDataSummaryTest>());
                    }
                    @SuppressWarnings("unchecked")
                    List<TollDataSummaryTest> children = (List<TollDataSummaryTest>) parent.getChildren();
                    children.add(node);
                }
            } else {
                rootNodes.add(node);
            }
        }
        
        return rootNodes;
    }
    
    /**
     * 同步数据到正式表
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollDataSummaryTest:syncToTollDataSummary')")
    @Log(title = "收费数据汇总测试", businessType = BusinessType.UPDATE)
    @PostMapping("/syncToTollDataSummary")
    public AjaxResult syncToTollDataSummary()
    {
        try {
            String result = tollDataSummaryTestService.syncDataToTollDataSummary();
            return success(result);
        } catch (Exception e) {
            return error("数据同步失败：" + e.getMessage());
        }
    }
}
